<!--
 * @Author: Neko
 * @Date: 2021-04-16 09:40:29
 * @LastEditTime: 2021-07-28 10:42:03
 * @LastEditors: Neko
-->
<template>
  <view id="__order-form">
    <web-view
      class="view"
      v-if="routerParams.type === 'goodiesPay'"
      :src="'/hybrid/html/form.html?order_id=' + orderId + '&token=' + token + '&platform=' + platform + '&url=' + url"
    />
    <web-view
      class="view"
      v-if="routerParams.type === 'pacyPay'"
      :src="'/hybrid/html/pacyPay.html?order_id=' + orderId + '&token=' + token + '&platform=' + platform + '&url=' + url"
    />
    <web-view
      class="view"
      v-if="routerParams.type === 'payPal'"
      :src="'/hybrid/html/payPal.html?order_id=' + orderId + '&token=' + token + '&platform=' + platform + '&url=' + url"
    />
    <web-view
      v-if="routerParams.type === 'checkout'"
      :src="
        '/hybrid/html/checkout.html?order_id=' + orderId + '&token=' + token + '&platform=' + platform + '&url=' + url
      "
    />

    <web-view
      v-if="routerParams.type === 'oceanPay'"
      :src="'/hybrid/html/oceanPay.html?order_id=' + orderId + '&token=' + token + '&platform=' + platform + '&url=' + url"
    />
  </view>
</template>

<script>
import { baseUrl } from '@/config'
import { getPaymentDetail, getPayPalPaymentDetail, getOceanPayDetail } from '@/api/http/order.js'

export default {
  computed: {
    orderId() {
      return this.routerParams.order_id
    },

    token() {
      return this.routerParams.token
    },

    platform() {
      // #ifdef H5
      return 'h5'
      // #endif

      // #ifndef H5
      return 'app'
      // #endif
    },

    url() {
      return encodeURIComponent(baseUrl())
    }
  },

  data() {
    return {
      routerParams: {}
    }
  },

  onLoad(opt) {
    this.routerParams = opt

    // #ifdef H5
    this.removeWebView()
    if (this.routerParams.type === 'pacyPay') {
      this.handlePacyPayAction()
    }

    if (this.routerParams.type === 'payPal') {
      this.handlePayPalAction()
    }

    if (this.routerParams.type === 'oceanPay') {
      this.handleOceanPayAction()
    }

    if (this.routerParams.type === '')
      window.addEventListener('popstate', this.popstateFunc)
    // #endif
  },

  methods: {
    removeWebView() {
      const orderForm = document.querySelector('#__order-form')
      const views = document.querySelectorAll('#__order-form .view')
      views.forEach(current => {
        orderForm.removeChild(current)
      })
    },

    popstateFunc() {
      // #ifdef H5
      history.pushState(null, null, location.href)
      // #endif
    },

    async handlePacyPayAction() {
      const res = await getPaymentDetail({
        orderId: this.orderId,
        url: window.location.protocol + '//' + window.location.hostname,
        jumpUrl: '/pages/order/check/check'
      })

      if (res.code === 200) {
        // console.log(res.data)
        // this.handleResponse(res)
        window.location = res.data
      } else {
        return uni.showToast({
          title: res.message,
          icon: 'none'
        })
      }
    },

    async handlePayPalAction() {
      const res = await getPayPalPaymentDetail({
        orderId: this.orderId,
        url: window.location.protocol + '//' + window.location.hostname,
        jumpUrl: '/pages/order/check/check'
      })

      if (res.code === 200) {
        this.handleResponse(res)
      } else {
        return uni.showToast({
          title: res.message,
          icon: 'none'
        })
      }
    },

    async handleOceanPayAction() {
      const res = await getOceanPayDetail({
        orderId: this.orderId,
        url: window.location.protocol + '//' + window.location.hostname,
        jumpUrl: '/pages/order/check/check'
      })

      if(res.code === 200) {
        this.handleResponse(res, 'oceanPay')
      } else {
        return uni.showToast({
          title: res.message,
          icon: 'none'
        })
      }
    },

    handleResponse(data, key) {
      const serializer = obj => {
        return Object.entries(obj)
          .reduce((prev, [key, value]) => {
            prev.push(key + '=' + value)
            return prev
          }, [])
          .join('&')
      }

      function oceanPayCharacterEscape(params) {
        return params
          .toString()
          .trim()
          .replace(/\</, '&lt;')
          .replace(/\>/, '&gt;')
          .replace(/\'/, '&#039;')
          .replace(/\\/, '&quot;')
      }

      const response = JSON.parse(data.data)

      const formAttr = [
        ['id', 'submit-form'],
        ['action', response.apiUrl],
        ['method', 'POST'],
        ['style', 'display: none'],
        // ['content-type', 'multipart/form-data']
      ]
      const form = document.createElement('form')

      formAttr.forEach(([key, value]) => {
        form.setAttribute(key, value)
      })

      const createInput = attrs => {
        const input = document.createElement('input')

        Object.entries(attrs).forEach(([key, value]) => {
          if (this.routerParams.type === 'oceanPay') {
            input.setAttribute(key, oceanPayCharacterEscape(value || ''))
            
          } else {
            input.setAttribute(key, value || '')
          }
          
        })

        return input
      }

      const fragment = document.createDocumentFragment()

      const inputAtt = Object.keys(response).map(val => ({
        key: val,
        val: response[val]
      }))

      inputAtt.forEach(current => {
        if (key === 'oceanPay') {
          if (current.key === 'apiUrl') return
          if (current.key === 'secureCode') return
          if (current.key === 'language') return
          if (current.key === 'order_notes') return
        }
        const input = createInput({
          name: current.key,
          value: current.val
        })
        fragment.appendChild(input)
      })

      form.appendChild(fragment)

      const button = document.createElement('button')
      button.type = 'submit'

      form.appendChild(button)

      document.body.appendChild(form)

      if (this.routerParams.type !== 'oceanPay') {
        form.submit()
      }
      
    }
  },

  destroyed() {
    // #ifdef H5
    window.removeEventListener('popstate', this.popstateFunc)

    // #endif
  }
}
</script>

<style lang="scss" scoped>
/* #ifdef H5 */
.view {
  display: none;
}
/* #endif */
</style>
